<?php


/*
 * This is my first OOP project. This is a test project!
 * The name of project is Bookstore. 
 */

/**
 * This class is handling information about users comments.
 * @author Velislav Belev
 * @license   http://opensource.org/licenses/gpl-3.0.html GNU Public License
 */
namespace Models;
class Comments extends \Models\User{
    
    public function publishComment($userId, $isLogged, $isSentForm, $newComment, $bookId) {
        
        $userId = (int)$userId;
        $userIdExists = $this->isInDb('users', 'user_id', $userId);
        if($userIdExists == 1 AND ($isLogged == 1 OR $isLogged == 2)) {
            if($isSentForm) {
                $newComment = $this->validate($newComment, 10, 'Your comment must be at least 10 characters long', 116);
                $bookId = $this->validate($bookId, 1, 'Invalid book', 117);
                $userId = $this->validate($userId, 1, 'Invalid user', 117);
                $isBookIdExist = $this->isInDb('books', 'book_id', $bookId);
                if($isBookIdExist == 1) {
                   $bookId = $this->escape($bookId); 
                   $newComment = $this->escape($newComment);
                   $userId = $this->escape($userId); 
                   $insertData = array('book_id' => $bookId, 'comment' => $newComment, 'user_id' => $userId); 
                   $isSaved = $this->insert('users_comments', $insertData);
                    if($isSaved != 0){
                        header ('Location: book.php?book_id='.$bookId);
                    } else {
                        throw new \Exception('Error in publishing comment', 116);
                    }
                }                
            }     
        } else {
             throw new \Exception('Only registered user can write comment', 115);
        }        
        
        
        
    }
    
    
    
    
    
    
    
}
